package com.swf.seed.triutil.jackson;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonUtil {
	public static <T>  String bean2Json(T bean) throws IOException{
		StringWriter sw = new StringWriter();
		ObjectMapper objectMapper = new ObjectMapper();
		JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(sw);
		jsonGenerator.writeObject(bean);
		return sw.toString();
		
	}
	public static <T> T json2Bean(String json,Class<T> t) throws JsonParseException, JsonMappingException, IOException{
		T bean=null ;
		ObjectMapper objectMapper = new ObjectMapper();
		bean = objectMapper.readValue(json, t);
		return bean;
	}
	public static void main(String[] args) throws IOException {
		Student s = new Student();
		s.setName("ZhangSan");
		List<String> bookList = new ArrayList<String>();
		bookList.add("水浒");
		bookList.add("三国");
		bookList.add("西游记");
		bookList.add("红楼梦");
		s.setBooks(bookList);
		s.setAge(111);
		String json = bean2Json(s);
		System.out.println(json);
		Student ss = json2Bean(json, Student.class);
		System.out.println(ss);
	}
}

class Student{
	private String name;
	private int age;
	private List<String> books;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public List<String> getBooks() {
		return books;
	}
	public void setBooks(List<String> books) {
		this.books = books;
	}
}